import {getToken,setToken,getUser,setUser,removeToken} from "@/utils/auth"
import {login,info,logout} from "@/api/login"

const user={
    state:{
        token:getToken(), //作为token的初始化值，以防每次刷新都会为空
        user:null,
    },
    mutations:{
        SET_TOKEN(state,token){
            state.token = token;
            setToken(state.token);
        },
        SET_USER(state,user){
            state.user = user;
        }
    },
    actions:{
        Login({commit},form){
            //resovle 触发成功处理 reject触发异常处理
            return new Promise((resolve,reject)=>{
                login(form.username.trim(),form.password).then(res=>{
                    const resp = res.data;
                    commit("SET_TOKEN",resp.data.token);
                    resolve(resp);
                })
            }).catch(error=>{
                reject(error);
            });
        },
        //通过token获取用户信息
        //注意state不要写在大括号外面
        GetUserInfo({commit,state}){
            return new Promise((resolve,reject)=>{
                info(state.token).then(res=>{
                    const resp = res.data;
                    commit("SET_USER",resp.data);
                    resolve(resp);
                }).catch(error=>{
                    reject(error);
                })
            })
        }
    }
}

export default user